package Algorithm.LICode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Solution {

    public static void main(String[] args) {
        int[] nums = new int[]{1, 5 , 6, 4};
        int target = 7;
        if (twoSum(nums,target) == null){
            System.out.println("sorry!!");
        }else {
            System.out.println(Arrays.toString(twoSum(nums, target)));
        }
        System.out.println(Arrays.toString(twoSum1(nums, target)));
    }

        /*
            自己的解法时间复杂度在O（n2）
         */
    public static int[] twoSum(int[] nums, int target){
        for (int i = 0; i < nums.length; i++) {
            for (int j = nums.length-1; j > i; j--) {
                if (nums[i]+nums[j] == target){
                    int[] t = new int[2];
                    t[0]=i;
                    t[1]=j;
                    return t;
                }
            }
        }
        return null;
    }

    // 官方做法
    public static int[] twoSum1(int[] nums, int target){
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i< nums.length; i++) {
            // 检查 hashMap 中是否存在指定的 key 对应的映射关系
            if(map.containsKey(target - nums[i])) {
                return new int[] {map.get(target-nums[i]),i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    }


